import time

from starlette.responses import RedirectResponse
from fastapi import FastAPI
from sqlmodel import SQLModel

from core.globals import site,sync_db
from core.settings import settings
import uvicorn
from admin_demo.backend.core.globals import auth
from fastapi_user_auth.auth.auth import *
from starlette.requests import Request
from sqlalchemy.orm import Session
from admin_demo.backend.core.globals import scheduler

app = FastAPI(debug=settings.debug)

# 安装应用
from apps import demo
from apps import nation

demo.setup(app.router, site)
nation.setup(app.router, site)

# 挂载后台管理系统
site.mount_app(app)


# 注意1: site.mount_app会默认添加site.db的session会话上下文中间件,如果你使用了其他的数据库连接,请自行添加.例如:
# from core.globals import sync_db
# app.add_middleware(sync_db.asgi_middleware) # 注意中间件的注册顺序.

# 注意2: 非请求上下文中,请自行创建session会话,例如:定时任务,测试脚本等.
# from core.globals import async_db
# async with async_db():
#     async_db.async_get(...)
#     async_db.session.get(...)
#     # do something

@app.on_event("startup")
async def startup():
    scheduler.start()
    # await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)

    # 创建默认管理员,用户名: admin,密码: admin, 请及时修改密码!!!
    # await auth.create_role_user("admin")
    # 创建默认超级管理员,用户名: root,密码: root, 请及时修改密码!!!
    await auth.create_role_user("root")
    # 运行site的startup方法,加载casbin策略等
    await site.router.startup()
    # 添加一条默认的casbin规则
    if not auth.enforcer.enforce("u:admin", site.unique_id, "page", "page"):
        await auth.enforcer.add_policy("u:admin", site.unique_id, "page", "page", "allow")
    pass


# @app.get("/auth/get_user")
# # @auth.requires()
# async def get_user(request: Request):
#     with Session(sync_db.engine) as session, session.begin():
#         role_key = "admin"
#         # create admin role
#         role = session.scalar(select(Role).where(Role.key == role_key))
#         if not role:
#             role = Role(key=role_key, name=f"{role_key} role")
#             print(role.name)
#             session.add(role)
#
#         # create admin user
#         user = session.scalar(select(auth.user_model).where(auth.user_model.username == role_key))
#         if not user:
#             user = auth.user_model(
#                 username=role_key,
#                 password=auth.pwd_context.hash(role_key),
#             )
#             print(user.username,  user.password)
#             session.add(user)
#         # create casbin rule
#         rule = session.scalar(
#             select(CasbinRule).where(
#                 CasbinRule.ptype == "g",
#                 CasbinRule.v0 == "u:" + role_key,
#                 CasbinRule.v1 == "r:" + role_key,
#             )
#         )
#         if not rule:
#             rule = CasbinRule(ptype="g", v0="u:" + role_key, v1="r:" + role_key)
#             print(rule.v0, rule.v1)
#             session.add(rule)
#         # auth._create_role_user_sync(session, "admin")
#     return request.user

@app.get('/')
async def index(request: Request):
    return RedirectResponse(url=site.router_path)



if __name__ == '__main__':
    uvicorn.run("main:app", port=8000, reload=True)
